﻿using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using NLog;

namespace Ensemble2D.Forms
{
    public partial class SplashScreen : Form
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();
        private bool recover = false;
        public SplashScreen(bool cover)
        {
            InitializeComponent();
            recover = recover;
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            mainFormLoader.RunWorkerAsync(this);
        }

        private void mainFormLoader_Dowork(object sender, DoWorkEventArgs e)
        {
            var screen = e.Argument as SplashScreen;

            Thread.Sleep(50);
            object result = screen.Invoke(new Func<MainForm>(screen.InitEditor));

            e.Result = result;
        }

        private MainForm InitEditor()
        {
            try
            {
                var main = new MainForm();
                EnsembleEditorApp.Init(main,recover);
                return main;
            }
            catch (Exception e)
            {
                logger.Info("初始化编辑器出错: {0}",e.Message);
                return null;
            }
        }

        private void mainFormLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Hide();
            try
            {
                var mainForm = e.Result as MainForm;
                if (mainForm != null)
                {
                    mainForm.Show();
                }
            }
            catch (Exception)
            {
                Application.Exit();
            }
            finally
            {
                Close();
            }
        }

        
    }
}
